/*
 * @Author: LIFM0623 1944099171@qq.com
 * @Date: 2024-03-29 15:41:37
 * @LastEditors: LIFM0623 1944099171@qq.com
 * @LastEditTime: 2024-03-29 20:36:37
 * @FilePath: \scene_back_nest\src\audio\audio.service.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Injectable } from '@nestjs/common';
import { Audio } from './entities/audio.entity';
import { CreateAudioDto, RawAudioDto } from './dto/create-audio.dto';
import { UpdateAudioDto } from './dto/update-audio.dto';
import { Repository, In } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { FileUtil } from '../common/file';

@Injectable()
export class AudioService {

  constructor(
    @InjectRepository(Audio)
    private readonly audioRepository: Repository<Audio>,
  ) {}
  async create(rawAudioDto: RawAudioDto) {
    const audio = this.audioRepository.create(rawAudioDto);
    const insertRes = await this.audioRepository.insert(audio);
    return insertRes.raw;
  }

  async createForScript(rawAudioDto: RawAudioDto) {
    const audio = this.audioRepository.create(rawAudioDto);
    const insertRes = await this.audioRepository.insert(audio);
    return insertRes.raw[0].id;
  }

  async findAll(): Promise<Audio[]> {
    return this.audioRepository.find();
  }

  async findByIds(ids: string[]): Promise<Audio[]> {
    return this.audioRepository.find({
      where: {
        id: In(ids), // 使用TypeORM的In操作符
      },
    });
  }

  async findOne(id: string): Promise<Audio> {
    return this.audioRepository.findOne({ where: { id: id } });
  }

  async update(id: string, updateAudioDto: UpdateAudioDto) {
    // 查找旧的用户实体
    const oldAudio = await this.audioRepository.findOne({
      where: { id: id },
    });
    if (!oldAudio) {
      return '该音频条目不存在';
    }
    const updateAudio = this.audioRepository.merge(oldAudio, updateAudioDto);
    await this.audioRepository.save(updateAudio);
    return '修改音频条目属性成功!';
  }

  async remove(id: string) {
    try {
      const result = await this.audioRepository.delete({ id: id });
      if (result.affected && result.affected > 0) {
        return `成功删除 ${result.affected} 条记录`;
      } else {
        return `未找到匹配的记录，没有进行删除操作`;
      }
    } catch (err) {
      console.error('删除记录失败', err);
      throw '删除记录失败';
    }
  }
}
